﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace AIC_KQKT
{
    public partial class BaoCaoMau2_B : MyFromBase
    {
        private static int KyBaoCao = -1;
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                Config();
                if (Request.QueryString["KyBaoCao"] != null)
                {
                    KyBaoCao = Convert.ToInt32(Request.QueryString["KyBaoCao"]);
                }
                InitialData();
                BindDataToControls();
            }



        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("BaoCaoMau2");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        /// <summary>
        /// Thủ tục cấu hình giao diện, các controls
        /// </summary>
        private void Config()
        {
            //TODO
            txtNguoiLapBaoCao.Text = "";
            txtThuTruongCoQuanChinhTri.Text = "";

        }

        /// <summary>
        /// Bind Data vào các contrls như Combobox, ListBox, textBox ...
        /// </summary>
        private void BindDataToControls()
        {
            //TODO
            if (Session["userid"] != null)
            {

                string sql = "Select DV.* " +
                             "From tblDonVi DV " +
                             "Inner Join tblUser U On U.DonViID=DV.ID " +
                             "Where U.ID=" + Session["userid"];
                DataTable dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                tdTenDonVi.InnerText = "(" + dtDV.Rows[0]["MaDV"] + ") " + dtDV.Rows[0]["TenDV"];
                dtDV = null;
                dtDV = new DataTable();
                sql = "Select ID,TenDM From tblDanhMuc Where ID = " + KyBaoCao;
                dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                lblKyBaoCao.InnerText = dtDV.Rows[0][1].ToString();
            }
        }

        protected void BindDataToTextField()
        {
            string sql = "SELECT CM_NguoiLapBieu,CM_ThuTruong,CM_ThoiGianBaoCao FROM dbo.tblBaoCaoMau2 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID AND IsCommon = 1";
            List<SqlParameter> lstParameters = new List<SqlParameter>();
            lstParameters.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
            lstParameters.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameters);
            if (dt.Rows.Count != 0)
            {
                txtNguoiLapBaoCao.Text = dt.Rows[0]["CM_NguoiLapBieu"].ToString();
                txtThuTruongCoQuanChinhTri.Text = dt.Rows[0]["CM_ThuTruong"].ToString();
                txtNgayBaoCao.Text = Convert.ToDateTime(dt.Rows[0]["CM_ThoiGianBaoCao"]).ToString("dd/MM/yyyy");
            }
        }

        /// <summary>
        /// Bind Data vào gridview
        /// </summary>
        private void BindDataToGrid()
        {
            List<SqlParameter> lstParams = new List<SqlParameter>();
            string sql = "SELECT M1.ID,B.TenDM AS DMCha,A.TenDM,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,F13,F14,F15,A.BoiDen " +
                         "FROM dbo.tblBaoCaoMau2 M1 INNER JOIN dbo.tblDanhMucBaoCao A ON M1.TenBaoCaoID_DM = A.ID " +
                         "INNER JOIN dbo.tblDanhMucBaoCao B ON A.FatherID = B.ID " +
                         "WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID AND B.LaToChuc = 1";
            lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
            lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
            lstParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParams);
            grvData.DataSource = dt;
            grvData.DataBind();
            btnLuu.Visible = true;
            grvData.Visible = true;
        }

        public void MergeRows(GridView gridView)
        {
            for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow row = gridView.Rows[rowIndex];
                GridViewRow previousRow = gridView.Rows[rowIndex + 1];

                if (row.Cells[0].Text == previousRow.Cells[0].Text)
                {
                    row.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 2 ? 2 : previousRow.Cells[0].RowSpan + 1;
                    previousRow.Cells[0].Visible = false;
                    row.Cells[0].CssClass = "RotateText";
                }
            }
        }

        #region Events

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }

        protected void InitialData()
        {
            grvData.EditIndex = -1;
            BindDataToGrid();
            if (((DataTable)grvData.DataSource).Rows.Count == 0)
            {
                SqlTransaction MyTran = SqlHelper.BeginTransaction();
                try
                {
                    List<SqlParameter> lstParams = new List<SqlParameter>();
                    lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
                    lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
                    lstParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                    string sql = "INSERT INTO dbo.tblBaoCaoMau2( KyBaoCaoID_DM ,DonViID ,TenBaoCaoID_DM ,F1 ,F2 ,F3 ,F4 ,F5 ,F6 ,F7 , " +
                             "F8 ,F9 ,F10 ,F11 ,F12 ,F13 ,F14 ,F15 ,UserID)   " +
                             "SELECT @KyBaoCaoID_DM ,@DonViID ,B.ID,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,@UserID FROM dbo.tblDanhMucBaoCao A " +
                             "INNER JOIN dbo.tblDanhMucBaoCao B ON A.ID = B.FatherID WHERE B.LaToChuc = 0 AND B.MaDM = 88" +
                             "GROUP BY A.TenDM,B.TenDM,A.ID,B.ID ORDER BY A.ID,B.ID";
                    SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql, lstParams);
                    MyTran.Commit();
                }
                catch
                {
                    MyTran.Rollback();
                }
                grvData.EditIndex = -1;
                BindDataToGrid();
            }
            else
            {
                BindDataToTextField();
                grvData.Visible = true;
            }
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {

            string sSQL = "UPDATE tblBaoCaoMau2 SET CM_NguoiLapBieu=@CM_NguoiLapBieu,CM_ThuTruong=@CM_ThuTruong,CM_ThoiGianBaoCao=CONVERT(DATETIME,@CM_ThoiGianBaoCao,103) " +
                            "WHERE IsCommon=1 AND DonViID=" + MyCommon.GetDonViID(Session["userid"].ToString()) + " And KyBaoCaoID_DM=" + KyBaoCao;

            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_NguoiLapBieu", SqlDbType.NVarChar, ParameterDirection.Input, txtNguoiLapBaoCao.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThuTruong", SqlDbType.NVarChar, ParameterDirection.Input, txtThuTruongCoQuanChinhTri.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThoiGianBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtNgayBaoCao.Text.Trim()));


            SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);

            MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);

        }

        #endregion Events


        #region GridCommand

        private static void AddMergedCells(GridViewRow objgridviewrow, TableCell objtablecell, int colspan, int rowspan, string celltext)
        {
            objtablecell = new TableCell();
            objtablecell.Text = celltext;
            objtablecell.ColumnSpan = colspan;
            objtablecell.RowSpan = rowspan;
            objtablecell.HorizontalAlign = HorizontalAlign.Center;
            objgridviewrow.Cells.Add(objtablecell);
        }

        protected void grvData_RowCreated(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.Header)
            {

                GridView objGridView = (GridView)sender;
                //GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);

                GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
                GridViewRow objgridviewrow2 = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
                GridViewRow objgridviewrow4 = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);

                TableCell objtablecell = new TableCell();
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Số TT");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "ĐỐI TƯỢNG");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Tổng số tổ chức đảng được giám sát");
                AddMergedCells(objgridviewrow, objtablecell, 5, 1, "CẤP GIÁM SÁT");
                AddMergedCells(objgridviewrow, objtablecell, 7, 1, "NỘI DUNG");
                AddMergedCells(objgridviewrow, objtablecell, 2, 1, "KẾT QUẢ");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Sửa");
                objgridviewrow.BackColor = System.Drawing.Color.FromArgb(0x10, 0x9A, 0xEA);
                objGridView.Controls[0].Controls.AddAt(0, objgridviewrow);

                objtablecell = new TableCell();
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "<div class='RotateText'>Quân ủy trung ương</div>");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "<div class='RotateText'>Đảng ủy trực thuộc QUTW</div>");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "<div class='RotateText'>Đảng ủy cấp trên trực tiếp cơ sở</div>");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "<div class='RotateText'>Đảng ủy cơ sở</div>");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "<div class='RotateText'>Đảng ủy bộ phận</div>");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Việc lãnh đạo, chỉ đạo, tổ chức thực hiện chủ trương, đường lối của Đảng, NQ, CT, quy định, quyết định, kết luận của cấp ủy cấp trên và cấp mình chính sách, PL của NN");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Việc thực hiện nguyên tắc tổ chức và hoạt động của Đảng(nguyên tắc tập trung dân chủ)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Việc thực hiện nhiệm vụ, quyền hạn được giao");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Việc thực hiện quy chế làm việc của cấp ủy cấp mình");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Công tác cán bộ");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Các nội dung khác");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Cộng");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Số tổ chức Đảng phát hiện có dấu hiệu vi phạm");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Số tổ chức Đảng chuyển kiểm tra dấu hiệu vi phạm");
                objgridviewrow2.BackColor = System.Drawing.Color.FromArgb(0x10, 0x9A, 0xEA);
                objGridView.Controls[0].Controls.AddAt(1, objgridviewrow2);

                objtablecell = new TableCell();
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "A");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "B");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "1");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "2");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "3");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "4");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "5");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "6");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "7");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "8");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "9");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "10");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "11");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "12");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "13");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "14");
                AddMergedCells(objgridviewrow4, objtablecell, 1, 1, "15");
                objgridviewrow4.BackColor = System.Drawing.Color.FromArgb(0xC7, 0xF4, 0x9C);
                objGridView.Controls[0].Controls.AddAt(2, objgridviewrow4);
            }
        }

        protected void grvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView dtr = (DataRowView)e.Row.DataItem;
                string[] BoiDen = dtr.Row.ItemArray[18].ToString().Split(',');
                if (BoiDen.Length >= 1)
                {
                    if (!BoiDen[0].Equals(""))
                    {
                        for (int i = 0; i < BoiDen.Length; i++)
                        {

                            e.Row.Cells[Convert.ToInt32(BoiDen[i]) + 1].BackColor = System.Drawing.Color.LightGray;
                            e.Row.Cells[Convert.ToInt32(BoiDen[i]) + 1].Enabled = false;
                        }
                    }
                }
            }
            RowDataBound(sender, e);
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;

            if ((sCommandName == AIC_KQKT.MyConst.Action.Approve))
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                for (int i = 3; i <= 16; i++)
                {
                    if (i != 14)
                    {
                        TextBox txtField = (TextBox)grvData.Rows[grvData.EditIndex].Cells[i].Controls[0];
                        arrParams.Add(SqlHelper.CreateParameterObject("F" + (i - 1), SqlDbType.Float, ParameterDirection.Input, txtField.Text));
                    }
                }
                string sql = "UPDATE tblBaoCaoMau2 SET [F1]=@F2+@F3+@F4+@F5+@F6,[F2]=@F2,[F3]=@F3," +
                             "[F4]=@F4,[F5]=@F5,[F6]=@F6,[F7]=@F7,[F8]=@F8,[F9]=@F9,[F10]=@F10,[F11]=@F11," +
                             "[F12]=@F12,[F13]=@F7+@F8+@F9+@F10+@F11+@F12,[F14]=@F14,[F15]=@F15, " +
                             "[UpdateDate]=GETDATE(),[UserID]=@UserID WHERE ID=@ID ";
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(sID)));
                int C1 = Convert.ToInt32(arrParams[0].Value) + Convert.ToInt32(arrParams[1].Value) + Convert.ToInt32(arrParams[2].Value) + Convert.ToInt32(arrParams[3].Value) + Convert.ToInt32(arrParams[4].Value);
                int C13 = Convert.ToInt32(arrParams[5].Value) + Convert.ToInt32(arrParams[6].Value) + Convert.ToInt32(arrParams[7].Value) + Convert.ToInt32(arrParams[8].Value) + Convert.ToInt32(arrParams[9].Value) + Convert.ToInt32(arrParams[10].Value);
                int C14 = Convert.ToInt32(arrParams[13].Value);
                int C15 = Convert.ToInt32(arrParams[14].Value);
                if (C1 > C13 || C1 < C14 || C14 < C15 || C1 < C15)
                {
                    string mess = "Có sai sót trong dữ liệu nhập vào, chú ý ! <br/>" +
                                  "C1 <= C2 + C3 + C4 + C5 + C6" +
                                  "C1 >= C14 >= C15" +
                                  "<br /> Bạn vừa nhập C1 = " + C1 + " ;C2 + C3 + C4 + C5 + C6 = " + C13 + " ;C14 = " + C14 + " và C15 = " + C15;
                    MyCommon.AddMessage(this.Master, mess, MyConst.MessageType.Warning);
                }
                else
                {
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                    MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);
                }
                // cap nhat vao database

                grvData.EditIndex = -1;
                BindDataToGrid();
            }
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {

            grvData.EditIndex = e.NewEditIndex;
            BindDataToGrid();
        }



        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //grvData.PageIndex = e.NewPageIndex;
            //BindDataToGrid();
        }


        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            BindDataToGrid();
        }

        #endregion GridCommand

        protected void grvData_PreRender(object sender, EventArgs e)
        {
            //MergeRows(grvData);
        }

        protected void imgBack_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("BaoCaoMau2.aspx?KyBaoCao=" + KyBaoCao);
        }
    }
}
